<template>
    <div class="menu-check">
        <el-input v-model="keyword" placeholder="请输入关键字进行过滤" />
        <div class="menu-check__box">
        <el-tree  
        ref = 'tree'
        :data="data"
        :props="defaultProps"
        show-checkbox
        :filter-node-method="filterNode"
        node-key="id"   
        />
    </div>
    </div>
</template>



<script>
import { getMenuList } from "@/api/menu";
import { deepTree, isLeaf } from "@/utils";

export default {
  name: "menu-check",

  data() {
    return {
      // 关键字
      keyword: "",
      // menuList 数据
      list: [],

      defaultProps: {
        label: "name",
        children: "children",
      },
    };
  },

  computed: {
    // Tree组件需要的数据
    data() {
      // 转树形格式
      return deepTree(this.list);
    },
  },

  watch: {
    keyword(value) {
      this.$refs.tree.filter(value);
    },
  },

  methods: {
    refresh() {
     // console.log("MenuCheck refresh");
      getMenuList().then((data) => {
        this.list = data;
        console.log("MenuCheck refresh then");
        // 通知父组件
        this.$emit("ok");
      });
    },

    /**
     * 过滤节点的函数
     */
    filterNode(value, data) {
      return data.name.includes(value);
    },

    /**
     * 获取当前勾选的Keys集合，包含选中与半选中
     */
    get() {
      //
      const key1 = this.$refs.tree.getCheckedKeys();
      const key2 = this.$refs.tree.getHalfCheckedKeys();
      return [...key1, ...key2];
    },

    /**
     * 设置当前勾选的Keys集合
     */
    set(keys) {
      const newKeys = keys.filter((id) => isLeaf(this.list, id));
      // console.log("newKeys", newKeys);
      this.$refs.tree.setCheckedKeys(newKeys);
    },
  },

  created() {
    this.refresh();
  },
};
</script>

<style lang="scss" scoped>

.menu-check{
    width:100%;
    &__box {
        margin-top:10px;
        border:1px solid #dcdfe6;
        padding: 5px 0;
        background-color:#fff
    }
}
</style>